<template>
  <div class="home">
    <div class="header">设备唯一标识解决方案测试工具</div>
    <div class="wrap" ref="wrap" id="ffb7cefd-02cb-4853-8238-c0292cf988d5">
      <el-alert
          v-if="title[Ftype]"
          :title="title[Ftype]"
          type="success"
          effect="dark"
          :closable="false">
      </el-alert>
      <el-radio-group class="group" v-model="Ftype" @input="onRadioChange">
        <el-radio-button label="F-JS"></el-radio-button>
        <el-radio-button label="F-JS-Pro"></el-radio-button>
        <el-radio-button label="顶象"></el-radio-button>
        <el-radio-button label="表单缓存"></el-radio-button>
      </el-radio-group>

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span v-if="Ftype !== '表单缓存'">当前设备指纹ID</span>
          <span v-else>表单缓存结果</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="clearLocal">清除所有缓存</el-button>
        </div>
        <p>ID: {{ appId }}</p>
      </el-card>
    </div>
    <el-button type="primary" :disabled="!Ftype" style="margin-top: 20px" round @click="onSubmit">匿名提交答卷</el-button>
  </div>
</template>

<script>
import Fingerprint2 from 'fingerprintjs2' // 引入fingerprintjs2
import FingerprintJS from '@fingerprintjs/fingerprintjs' // 引入fingerprintjs3+
export default {
  name: 'HomeView',
  data() {
    return {
      Ftype: '',
      title: {
        'F-JS': 'FingerprintJS开源版-浏览器指纹',
        'F-JS-Pro': 'FingerprintJS商业版-浏览器指纹',
        '顶象': '顶象设备指纹-浏览器指纹',
        '表单缓存': '通过问卷id缓存实现'
      },
      baseUrl: 'FingerprintTest',
      appId: ''
    }
  },
  methods: {
    onRadioChange(val) {
      switch (val) {
        case 'F-JS':
          this.FJS()
          break
        case 'F-JS-Pro':
          this.FJSPRO()
          break
        case '顶象':
          this.DX()
          break
        case '表单缓存':
          this.FormId()
          break
      }
    },
    FormId() {
      const id = this.$refs.wrap.getAttribute('id')
      this.appId = id
    },
    toAlert(type) {
      const key = `${this.baseUrl}-${type}`
      const localKey = localStorage.getItem(key)
      if (localKey === this.appId) {
        this.$alert('当前问卷你已经回答过了， 无需再次回答！', '提示', {
          confirmButtonText: '确定',
          callback: action => {}
        })
      } else {
        localStorage.setItem(key, this.appId)
        this.$notify({
          title: '提示',
          type: 'success',
          message: '匿名提交成功~'
        });
      }
    },
    clearLocal() {
      const keys = ['formId', 'DX', 'FJS', 'FJSPRO']
      let num = keys.length
      keys.forEach(key => {
        num--
        const localKey = `${this.baseUrl}-${key}`
        localStorage.removeItem(localKey)
        if(num === 0) {
          this.Ftype = ''
          this.appId = ''
          this.$notify({
            title: '提示',
            type: 'success',
            message: '缓存记录清除完毕~'
          });
        }
      })
    },
    FJS() {
      // // 浏览器指纹 v2.0 写法 -- 放开注释即可使用
      // const fingerprint = Fingerprint2.get((components) => { // 参数只有回调函数时，默认浏览器指纹依据所有配置信息进行生成
      //   const values = components.map(component => component.value); // 配置的值的数组
      //   const murmur = Fingerprint2.x64hash128(values.join(''), 31); // 生成浏览器指纹
      //   console.log(murmur);
      //   this.appId = murmur
      // });
      // 浏览器指纹 v3.0 写法 -- 放开注释即可使用
      const fpPromise = FingerprintJS.load();
      (async () => {
        const fp = await fpPromise
        const result = await fp.get()
        this.appId = result.visitorId
      })()
    },
    FJSPRO() {
      const fpPromise = new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.onload = resolve
        script.onerror = () => reject('Failed to load the script')
        script.async = true
        script.src = 'https://cdn.jsdelivr.net/npm/'
            + '@fingerprintjs/fingerprintjs-pro@3/dist/fp.min.js'
        document.head.appendChild(script)
      })
          .then(() => FingerprintJS.load({
            // Get a token at https://dashboard.fingerprintjs.com
            // Wait a couple of seconds before a result appears
            token: 'sample_docs_token',
            // region: 'eu',
            // endpoint: 'https://fp.your.com',
          }))
      fpPromise
          .then(fp => fp.get())
          .then(result => {
            const visitorId = result.visitorId
            this.appId = visitorId
          })
          .catch(error => console.error(error))
    },
    DX() {
      const options = {
        appId: '3c12059936da2e2e4c519faa908389b8', // 唯一标识，必填
        // server: 'https://constid.dingxiang-inc.com/udid/c1', // constId 服务接口，可选
        userId: 'Penn' // 用户标识，可选
      }
      _dx.ConstID(options, (err, token) => {
        if (err) {
          console.log('error: ' + err)
          return
        }
        this.appId = token
      })
    },
    onSubmit() {
      let type = ''
      switch (this.Ftype) {
        case 'F-JS':
          type = 'FJS'
          break
        case 'F-JS-Pro':
          type = 'FJSPRO'
          break
        case '顶象':
          type = 'DX'
          break
        case '表单缓存':
          type = 'formId'
          break
      }
      this.toAlert(type)
    }
  },
  mounted() {
  }
}
</script>
<style lang="scss" scoped>
.home {
  .header {
    width: 100%;
    height: 46px;
    line-height: 46px;
    background: #409EFF;
    font-size: 16px;
    font-weight: bold;
    color: #fff;
  }

  .wrap {
    margin-top: 10px;
    padding: 0 20px;
  }

  .group {
    margin-top: 5%;
  }

  .box-card {
    margin-top: 10%;

    p {
      text-align: left;
      overflow-wrap: break-word;
    }
  }
}
</style>
